package com.nanhai.buddhist.college.module.system.dal.mysql.permission;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.nanhai.buddhist.college.framework.mybatis.core.mapper.BaseMapperX;
import com.nanhai.buddhist.college.module.system.dal.dataobject.permission.UserRoleDO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Mapper
public interface UserRoleMapper extends BaseMapperX<UserRoleDO> {

    default List<UserRoleDO> selectListByUserId(String userId) {
        return selectList(UserRoleDO::getUserId, userId);
    }

    default List<UserRoleDO> selectListByRoleId(Long roleId) {
        return selectList(UserRoleDO::getRoleId, roleId);
    }

    default void deleteListByUserIdAndRoleIdIds(String userId, Collection<Long> roleIds) {
        LambdaQueryWrapper<UserRoleDO> objectLambdaQueryWrapper = Wrappers.lambdaQuery();
        objectLambdaQueryWrapper.eq(UserRoleDO::getUserId, userId);

        // 教师角色不允许删除
        Set<Long> collect = roleIds.stream().filter(s -> s.equals(3L)).collect(Collectors.toSet());
        objectLambdaQueryWrapper.in(UserRoleDO::getRoleId, collect);
        delete(objectLambdaQueryWrapper);
    }

    default void deleteListByUserId(String userId) {
        delete(new LambdaQueryWrapper<UserRoleDO>().eq(UserRoleDO::getUserId, userId));
    }

    default void deleteListByRoleId(Long roleId) {
        delete(new LambdaQueryWrapper<UserRoleDO>().eq(UserRoleDO::getRoleId, roleId));
    }


    default List<UserRoleDO> selectListByRoleIds(Collection<Long> roleIds) {
        return selectList(UserRoleDO::getRoleId, roleIds);
    }

    @Select("SELECT COUNT(*) FROM system_user_role WHERE update_time > #{maxUpdateTime}")
    Long selectCountByUpdateTimeGt(Date maxUpdateTime);

}
